package com.kuaimacode.kframework.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuaimacode.kframework.enums.DeviceTypeEnum;
import com.kuaimacode.kframework.mybatis.mapper.push.SysPushTokenMapper;
import com.kuaimacode.kframework.mybatis.models.push.SysPushToken;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.service
 * @Description: created by IntelliJ IDEA
 * @date 2019-04-07 15:50
 */
@Service
public class SysPushTokenService extends ServiceImpl<SysPushTokenMapper, SysPushToken> {

    /**
     * 根据用户ID查找数据
     * @param userId
     * @return
     */
    public SysPushToken findByUserId(Long userId) {
        QueryWrapper<SysPushToken> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 保存或更新设备token信息
     * @param userId
     * @param token
     * @param deviceTypeEnum
     */
    public void saveOrUpdate(Long userId, String token, DeviceTypeEnum deviceTypeEnum) {
        QueryWrapper<SysPushToken> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        SysPushToken pushToken = baseMapper.selectOne(wrapper);
        if (pushToken == null) {
            pushToken = new SysPushToken();
            pushToken.setDeviceType(deviceTypeEnum.getType());
            pushToken.setPushToken(token);
            pushToken.setUserId(userId);
            Date now = new Date();
            pushToken.setCreateAt(now);
            pushToken.setUpdateAt(now);
            baseMapper.insert(pushToken);
        } else {
            pushToken.setPushToken(token);
            pushToken.setDeviceType(deviceTypeEnum.getType());
            baseMapper.updateById(pushToken);
        }
    }
}
